package com.elitel.frame.base.controller;

import com.elitel.base.entity.sqlparse.InputParam;
import com.elitel.base.entity.sqlparse.SqlData;
import com.elitel.common.DESUtil;
import com.elitel.common.core.log.annotation.Log;
import com.elitel.common.core.log.enums.BusinessType;
import com.elitel.common.utils.StringUtils;
import com.elitel.common.utils.XCommonUtils;
import com.elitel.frame.base.component.RedisCatchBasicServer;
import com.elitel.frame.base.component.RedisCatchCensus;
import com.elitel.frame.base.service.*;
import com.elitel.frame.base.service.strategy.sql.OgnlParseSQLStrategy;
import com.elitel.frame.business.service.CensusSearchService;
import com.elitel.frame.main.entity.*;
import com.elitel.frame.main.entity.enums.ParseSQLEnum;
import com.elitel.frame.main.entity.ext.*;
import com.elitel.frame.main.entity.vo.JsonDataResult;
import com.elitel.frame.main.entity.vo.JsonResult;
import com.elitel.frame.main.entity.vo.PageResponseVo;
import com.elitel.frame.main.entity.vo.ServerTree;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "/system/server")
public class ServerController {
    private static final Logger logger = LoggerFactory.getLogger(ServerController.class);

    @Autowired
    private DBServerService dBServerServiceImpl;
    @Resource
    private CfgDbService cfgDbService;
    //  @Resource private RedisCacheService redisCacheService;
    @Resource
    private RedisCatchBasicServer redisCatchBasicServer;
    @Resource
    private CensusSearchService censusSearchServiceImpl;
    @Resource
    private RedisCatchCensus redisCatchCensus;

    // private static final RedisDbIndex rdi =RedisDbIndex.ZERO;
    @Autowired
    private BaseQueryfieldService baseQueryfieldService;

    @Autowired
    private CfgExtsqlService cfgExtSqlService;

    @Resource
    private OgnlParseSQLStrategy ognlParseSQLStrategy;


    @Resource
    private SysPrjServiceService sysPrjServiceService;



    /**
     * 增加服务
     *
     * @param servers
     * @param request
     * @return
     */
    @RequestMapping(
            value = "/insertServer",
            method = RequestMethod.POST,
            consumes = "application/json")
    @ResponseBody
    public Object insertServer(@RequestBody CfgExtSqlExt servers, HttpServletRequest request) {
        // 先校验服务id是否存在

        JsonResult jsonResult = checkService(servers);
        if (jsonResult != null) {
            return jsonResult;
        } else {
            jsonResult = new JsonResult();
        }

        Map<String, Object> map = new HashMap<String, Object>();

        String sqldes = servers.getSql();
//    logger.info("+++++++++加密前："+sqldes);
        String sql = DESUtil.decryption(sqldes, "12345678");
//    logger.info("+++++++++解密后："+sql);

//    String sql = Base64Util.baseConvertStr(sql64).replaceAll("-"," ");
        DBServer server = new DBServer();
        server.setGuid(servers.getGuid());
        server.setName(servers.getName());
        server.setDbKey(servers.getDbKey());
        server.setSql(sql);
        server.setRemake(servers.getRemake());
        server.setIsPaging(servers.getIsPaging());
        server.setCatched(servers.getCatched());
        server.setCatchTime(servers.getCatchTime());
        server.setParamtype(servers.getParamtype());
        server.setTimeDelay(servers.getTimeDelay() != null ? servers.getTimeDelay() : 0);
        server.setIsPaging(servers.getIsPaging());
        server.setResponseMode(servers.getResponseMode());

        String message = dBServerServiceImpl.insertServer(server);
        int result = 0;
        if ("success".equals(message)) {

            // TODO: 添加 SQL 中的查询字段
            List<BaseQueryfield> baseQueryfields = dBServerServiceImpl.parseSQLQueryField(server);
            if (baseQueryfields.size() > 0) {
                baseQueryfieldService.deleteQueryfieldByServiceId(servers.getGuid());
                baseQueryfieldService.batchInsertBaseQueryField(baseQueryfields);
            }
            Map<String, String> hashMap = new HashMap<>();
            if (server.getParamtype() == ParseSQLEnum.freemarker.getType()) {
                hashMap = XCommonUtils.extractPlaceHolderColumnObjectByParseSql(sql);
            } else {
                for (BaseQueryfield baseQueryfield : baseQueryfields) {
                    hashMap.put(baseQueryfield.getParametercode(), baseQueryfield.getParamformat());
                }
            }
            saveSqlFieldType(server, hashMap);

            // insertQueryField
            SysPrjservice sysPrjservice = new SysPrjservice();
            sysPrjservice.setGuid(UUID.randomUUID().toString());
            sysPrjservice.setPcode(servers.getHidProjectid());
            sysPrjservice.setServicetype(servers.getHidServertype());
            sysPrjservice.setServicecode(servers.getGuid());
            sysPrjservice.setSysDataLabelId(servers.getSysDataLabelId());
            sysPrjservice.setCacheDur(servers.getCacheDur());
            sysPrjservice.setApiPath(servers.getApiPath());
            sysPrjservice.setResCvsJs(servers.getResCvsJs());
            sysPrjservice.setTableCodes(servers.getTableCodes());
            sysPrjservice.setCreatedate(new Date());
            sysPrjservice.setServicename(servers.getName());
            result = dBServerServiceImpl.insertSystem(sysPrjservice);
        }

        if (result > 0) {
            message = "success";
        } else {
            message = "fail";
        }
        map.put("message", message);
        jsonResult.setData(map);
        jsonResult.setMsg("添加成功");
        jsonResult.setSuccess(true);
        return jsonResult;
    }


    private JsonResult checkService(CfgExtSqlExt servers) {
        String serviceCode = servers.getGuid();
        boolean exist = sysPrjServiceService.serviceCodeExist(null, serviceCode);
        if (exist) {
            JsonResult jsonResult = new JsonResult();
            jsonResult.setSuccess(false);
            jsonResult.setMsg("服务编码已存在，请重新填写！");
            return jsonResult;
        }
        if (StringUtils.isNotEmpty(servers.getApiPath())) {
            boolean flag = sysPrjServiceService.selectServiceApiCode(servers.getApiPath());
            if (flag) {
                JsonResult jsonResult = new JsonResult();
                jsonResult.setSuccess(false);
                jsonResult.setMsg("服务调用地址已存在，请重新填写！");
                return jsonResult;
            }
        }
        return null;
    }

    public void saveSqlFieldType(DBServer server, Map<String, String> columnObjectMap) {

        cfgExtSqlService.deleteByServiceId(server.getGuid());

        for (Map.Entry<String, String> columnObjectEntry : columnObjectMap.entrySet()) {
            BaseSqlFieldType baseSqlFieldType = new BaseSqlFieldType();
            baseSqlFieldType.setGuid(UUID.randomUUID().toString());
            baseSqlFieldType.setServiceId(server.getGuid());
            baseSqlFieldType.setFieldName(columnObjectEntry.getKey());
            baseSqlFieldType.setFieldJavaType(Optional.ofNullable(columnObjectEntry.getValue()).orElse(""));
            baseSqlFieldType.setCreateDate(new Date());
            int flag = cfgExtSqlService.insertBaseSqlFieldType(baseSqlFieldType);
        }

    }


    // here is provider all script sql to parse content
    @RequestMapping(value = "/parseScriptSqlFieldType", method = RequestMethod.GET)
    @ResponseBody
    public Object parseScriptSqlFieldType() {
        List<CfgExtsql> cfgExtSqlList = cfgExtSqlService.findAllScriptSql();

        Map<String, String> parseFieldType = new HashMap<>();
        for (CfgExtsql cfgExtSql : cfgExtSqlList) {

            Map<String, String> placeHolderOrderColumnObject = XCommonUtils.extractPlaceHolderColumnObjectByParseSql(cfgExtSql.getDtSql());
            placeHolderOrderColumnObject.forEach((fieldName, emptyfieldType) -> {
                parseFieldType.put(fieldName, "");
            });

        }
        // here is iterate all sql
        // every sql to parse map

        return parseFieldType;
    }

    /**
     * 增加查询字段
     *
     * @param baseQueryfield
     * @param request
     * @return
     */
    @RequestMapping(
            value = "/insertField",
            method = RequestMethod.POST,
            consumes = "application/json")
    @ResponseBody
    public String insertField(
            @RequestBody BaseQueryfield baseQueryfield, HttpServletRequest request) {
        String message = dBServerServiceImpl.insertField(baseQueryfield);
        return message;
    }

    /**
     * 获取所有查询字段
     *
     * @param request
     * @return
     */
    @RequestMapping("/selectAllFiled")
    @ResponseBody
    public List<QueryFiled> selectAllFiled(HttpServletRequest request) {
        String serviceID = request.getParameter("sysId");
        List<QueryFiled> queryFieldList = new ArrayList<>();

        List<BaseSqlFieldType> sqlFieldTypeList = cfgExtSqlService.findByServiceId(serviceID);
        for (BaseSqlFieldType baseSqlFieldType : sqlFieldTypeList) {
            QueryFiled queryField = new QueryFiled();
            queryField.setGuid(baseSqlFieldType.getGuid());
            queryField.setParametercode(baseSqlFieldType.getFieldName());
            queryField.setFieldJavaType(baseSqlFieldType.getFieldJavaType());
            queryField.setServiceid(serviceID);
            queryField.setNote(baseSqlFieldType.getNote());
            queryFieldList.add(queryField);
        }
        baseQueryfieldService.selectSqlRequiredFields(serviceID, queryFieldList);
        return queryFieldList;
    }

    /**
     * 删除服务
     *
     * @param request
     * @return
     */
    @RequestMapping("/deleteServer")
    @ResponseBody
    public Object deleteServer(HttpServletRequest request) {
        JsonResult jsonResult = new JsonResult();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
      /*String id = new String(request.getParameter("keys").getBytes(
      "iso-8859-1"), "utf-8");*/
            String id = request.getParameter("keys");
            String message = dBServerServiceImpl.deleteServer(id);
            map.put("message", message);
            jsonResult.setMsg("删除成功");
            jsonResult.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setMsg("删除失败");
            jsonResult.setSuccess(false);
        }

        return jsonResult;
    }

    /**
     * 根据数据库标识查询所有的服务
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/selectServer", method = RequestMethod.GET)
    @ResponseBody
    public Object selectServer(HttpServletRequest request) {
        JsonResult jsonResult = new JsonResult();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
      /*String dbKey = new String(request.getParameter("dbKey").getBytes(
      "iso-8859-1"), "utf-8");*/
            String dbKey = request.getParameter("dbKey");
            List<DBServer> serverList = dBServerServiceImpl.selectServer(dbKey);
            map.put("list", serverList);
            jsonResult.setMsg("查找成功");
            jsonResult.setSuccess(true);
            jsonResult.setData(serverList);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setMsg("查找失败");
            jsonResult.setSuccess(false);
        }
        return jsonResult;
    }

    /**
     * cfg_extsql表根据dt_dbkey去重
     *
     * @param request
     * @return
     */
    @RequestMapping("/seleDBName")
    @ResponseBody
    public List<ServerTree> selectAllDB(HttpServletRequest request) {
        List<ServerTree> list = dBServerServiceImpl.selectDbName();
        return list;
    }

    /**
     * 根据服务id获取服务信息
     *
     * @param request
     * @return
     */
    @RequestMapping("/seleServerOne")
    @ResponseBody
    public DBServer selectServerOne(HttpServletRequest request) {
        String guid = request.getParameter("key");
        // System.err.println("+++++++++++" + guid + "+++++++++++++++++++");
        DBServer server = dBServerServiceImpl.selectServerOne(guid);
        return server;
    }

    /**
     * 修改脚本服务信息
     *
     * @param server
     * @param request
     * @return
     */
    @RequestMapping(
            value = "/updateServering",
            method = RequestMethod.POST,
            consumes = "application/json")
    @ResponseBody
    @Log(title = "修改脚本服务信息", businessType = BusinessType.UPDATE)
    public Object updateServer(@RequestBody DBServerExt server, HttpServletRequest request) {
        JsonResult jsonResult = new JsonResult();
        Map<String, Object> map = new HashMap<String, Object>();
        String sqldes = server.getSql();
//    logger.info("+++++++++加密前："+sqldes);
        String sql = DESUtil.decryption(sqldes, "12345678");
//    logger.info("+++++++++解密后："+sql);
//    String sql = Base64Util.baseConvertStr(servers.getSql()).replaceAll("-"," ");
        server.setSql(sql);

        try {
            String message = dBServerServiceImpl.updateServer(server);
            if ("success".equals(message)) {

                // TODO: 添加 SQL 中的查询字段
                List<BaseQueryfield> baseQueryfields = dBServerServiceImpl.parseSQLQueryField(server);
                baseQueryfieldService.deleteQueryfieldByServiceId(server.getGuid());
                if (baseQueryfields.size() > 0) {
                    baseQueryfieldService.batchInsertBaseQueryField(baseQueryfields);
                }
                Map<String, String> hashMap = new HashMap<>();
                if (server.getParamtype() == ParseSQLEnum.freemarker.getType()) {
                    hashMap = XCommonUtils.extractPlaceHolderColumnObjectByParseSql(sql);
                } else {
                    for (BaseQueryfield baseQueryfield : baseQueryfields) {
                        hashMap.put(baseQueryfield.getParametercode(), baseQueryfield.getParamformat());
                    }
                }
                // here find before column find exclude column
                saveSqlFieldType(server, hashMap);
            }
            map.put("message", message);
            jsonResult.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
        }
        return jsonResult;
    }

    /**
     * 通过数据库标识查询所有的脚本服务信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getExtSqlList")
    @ResponseBody
    public List<CfgExtsql> getExtSqlList(HttpServletRequest request) {
        String dbkey = request.getParameter("dbkey");
        String searchkey = request.getParameter("searchkey");
    /*try {
    	searchkey = new String((request.getParameter("searchkey")).getBytes("iso-8859-1"),"utf-8");
    } catch (UnsupportedEncodingException e) {
    	e.printStackTrace();
    }*/
        List<CfgExtsql> list = dBServerServiceImpl.getExtSqlList(dbkey, searchkey);
        return list;
    }

    /**
     * 查询数据源树形数据
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/treeList")
    @ResponseBody
    public Object selectField(HttpServletRequest request) {
        JsonResult jsonResult = new JsonResult();
        try {
            List<Census> list = dBServerServiceImpl.selectField();
            jsonResult.setMsg("查找成功");
            jsonResult.setSuccess(true);
            jsonResult.setData(list);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setMsg("查找失败");
            jsonResult.setSuccess(false);
        }
        return jsonResult;
    }

    /**
     * 分页查询脚本信息
     *
     * @param request
     * @return
     */
    @RequestMapping("/paging")
    @ResponseBody
    public Object getFenye(HttpServletRequest request) {
        PageResponseVo<DBServer> pagelist = null;
        JsonResult jsonResult = new JsonResult();
        try {
      /*String dbKey = new String(request.getParameter("dbKey").getBytes(
      		"iso-8859-1"), "utf-8");

      String pageSize = new String(request.getParameter("pageSize")
      		.getBytes("iso-8859-1"), "utf-8");*/

            String dbKey = request.getParameter("dbKey");
            String pageSize = request.getParameter("pageSize");
            String pageNo = String.valueOf(1);
            pagelist = dBServerServiceImpl.selectFenye(dbKey, pageNo, pageSize);
            jsonResult.setData(pagelist);
            jsonResult.setSuccess(true);
            jsonResult.setMsg("查找成功");
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setMsg("查找失败");
            jsonResult.setSuccess(false);
        }
        return jsonResult;
    }

    /**
     * @return true(存在), false(不存在)
     * @throws
     * @Title: isExsitByguid @Description: TODO(查询guid是否存在)
     * @author guoyanfei
     */
    @RequestMapping("/isExsitByguid")
    @ResponseBody
    public boolean isExsitByguid(HttpServletRequest request) {
        boolean result = false;
        try {
            String guid = request.getParameter("guid");
            DBServer server = dBServerServiceImpl.selectServerOne(guid);
            if (server != null && server.equals("") == false) {
                result = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 通过数据源标识查询表信息
     *
     * @param request
     * @return
     */
    @RequestMapping("/selectTableName")
    @ResponseBody
    public Object selectTableName(HttpServletRequest request) {
        JsonResult jsonResult = new JsonResult();
        Map<String, Object> map = null;
        try {
            String conn = request.getParameter("dbKey");
            map = dBServerServiceImpl.selectTableName(conn);
            jsonResult.setData(map);
            jsonResult.setMsg("查找成功");
            jsonResult.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setMsg("查找失败");
            jsonResult.setSuccess(false);
        }
        return jsonResult;
    }

    /**
     * 根据数据源标识查询脚本服务信息
     *
     * @param request
     * @return
     */
    @RequestMapping("/selectServerOnes")
    @ResponseBody
    public Object selectServerOnes(HttpServletRequest request) {
        Map<String, Object> serverMap = new HashMap<String, Object>();
        JsonResult jsonResult = new JsonResult();
        try {
            String conn = request.getParameter("dbKey");
            DBServer dBServer = dBServerServiceImpl.selectServerOnes(conn);
            CfgDb cfgDb = cfgDbService.selectByKey(conn);
            PrjServiceExt prjServiceExt = sysPrjServiceService.getPrjServiceExt(dBServer.getGuid());
            serverMap.put("dbServer", dBServer);
            serverMap.put("prjServiceExt", prjServiceExt);

            return JsonDataResult.responseSuccess(serverMap, dBServer.getResponseMode());
        } catch (Exception e) {
            logger.error(e.getMessage());
            return JsonDataResult.responseError(e.getMessage());
        }
    }

    /**
     * 查询脚本服务查询字段
     *
     * @param request
     * @return
     */
    @RequestMapping("/selectServerColumn")
    @ResponseBody
    public List<BaseSqlconfig> selectServerColumn(HttpServletRequest request) {
        String pageNo = null;
        String pageSize = null;
        PageResponseVo<BaseSqlconfig> pageResponseVo = null;
        String conn = null;
        conn = request.getParameter("sysId");
        pageNo = String.valueOf(1);
        pageSize = String.valueOf(10);
        DBServer dBServer = dBServerServiceImpl.selectServerOnes(conn);
        CfgDb cfgDb = cfgDbService.selectByKey(dBServer.getDbKey());

        JsonResult baseSqlColumn =
                censusSearchServiceImpl.getBaseSqlColumn(
                        cfgDb, pageNo, pageSize, dBServer.getSql(), dBServer.getDbKey(), conn, dBServer.getParamtype());

        pageResponseVo = (PageResponseVo<BaseSqlconfig>) baseSqlColumn.getData();

        for (int i = 0; i < pageResponseVo.getRows().size(); i++) {
            if (null == pageResponseVo.getRows().get(i).getIsqueryfield()) {
                pageResponseVo.getRows().get(i).setIsqueryfield((short) 0);
            }
            if (null == pageResponseVo.getRows().get(i).getQueryorder()) {
                pageResponseVo.getRows().get(i).setQueryorder(1);
            }
        }
        return pageResponseVo.getRows();
    }

    /**
     * 查询是否分页（暂时不用）
     *
     * @param request
     * @return
     */
    @RequestMapping("/selectServerColumnExit")
    @ResponseBody
    public JsonResult selectServerColumnExit(HttpServletRequest request) {
        JsonResult jsonResult = new JsonResult();
        try {
            String serviceID = request.getParameter("sysId");
            String sqlDES = request.getParameter("sql");
//      logger.info("+++++++++前端sql加密后："+sqlDES);
            String sql = DESUtil.decryption(sqlDES, "12345678");
//      logger.info("+++++++++解密后："+sql);
            String dbkey = request.getParameter("dbkey");
            String pageNo = String.valueOf(1);
            String pageSize = String.valueOf(10);
            CfgDb cfgDb = cfgDbService.selectByKey(dbkey);
            DBServer dBServer = dBServerServiceImpl.selectServerOnes(serviceID);
            JsonResult baseSqlColumn =
                    censusSearchServiceImpl.getBaseSqlColumn(cfgDb, pageNo, pageSize, sql, dbkey, serviceID, dBServer.getParamtype());

            if (!baseSqlColumn.getMsg().equals("")) {
//            if (baseSqlColumn.isSuccess() == false) {
                jsonResult.setMsg(baseSqlColumn.getMsg());
                jsonResult.setSuccess(false);
            } else {
                PageResponseVo<BaseSqlconfig> pageResponseVo =
                        (PageResponseVo<BaseSqlconfig>) baseSqlColumn.getData();
                jsonResult.setSuccess(true);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            jsonResult.setMsg(ex.getMessage());
        }
        return jsonResult;
    }

    /**
     * 删除查询字段
     *
     * @param request
     * @return
     */
    @RequestMapping("/deleteFiled")
    @ResponseBody
    public String deleteFiled(HttpServletRequest request) {
        String guid = request.getParameter("guid");
        String message = dBServerServiceImpl.deleteFiled(guid);
        return message;
    }

    /**
     * 查询脚本服务查询字段
     *
     * @param request
     * @return
     */
    @RequestMapping("/selectServerShintColumn")
    @ResponseBody
    public List<BaseSqlconfig> selectServerShintColumn(HttpServletRequest request) {
        String conn = request.getParameter("key");
        String config = request.getParameter("dbKey");
        PageResponseVo<BaseSqlconfig> pageResponseVo = dBServerServiceImpl.selectServerShintColumn(conn, config);
        return pageResponseVo.getRows();
    }

    /**
     * 保存显示字段
     *
     * @param baseSqlconfig
     * @param request
     * @return
     */
    @RequestMapping(
            value = "/saveBaseSqlConfig",
            method = RequestMethod.POST,
            consumes = "application/json")
    @ResponseBody
    public Object saveBaseSqlConfig(
            @RequestBody BaseSqlConfigXX[] baseSqlconfig, HttpServletRequest request) {
        String message = "";
        String xString = "";
        JsonResult jsonResult = new JsonResult();
        try {
            List<BaseSqlconfig> list2 = new ArrayList<BaseSqlconfig>();
            for (BaseSqlConfigXX x : baseSqlconfig) {
                BaseSqlconfig baseSqlconfig2 = new BaseSqlconfig();
                baseSqlconfig2.setGuid(x.getGuid());
                xString = x.getServiceid();
                baseSqlconfig2.setServiceid(x.getServiceid());
                baseSqlconfig2.setFiledname(x.getFiledname());
                baseSqlconfig2.setFieldcaption(x.getFieldcaption());
                baseSqlconfig2.setShoworder(x.getShoworder());
                baseSqlconfig2.setIsqueryfield(x.getIsqueryfield());
                // 这里判断是因为如果你选择字段是排序字段但是没有选择排序规则，这里默认是正序
                if (x.getIsqueryfield() != null
                        && Integer.valueOf(x.getIsqueryfield()) == 1
                        && x.getQueryorder() != null
                        && Integer.valueOf(x.getQueryorder()) != 1
                        && Integer.valueOf(x.getQueryorder()) != 0) {
                    baseSqlconfig2.setQueryorder(1);
                } else {
                    baseSqlconfig2.setQueryorder(x.getQueryorder());
                }
                baseSqlconfig2.setShowtype(x.getShowtype());
                baseSqlconfig2.setDtConfigId(x.getDtConfigId());
                baseSqlconfig2.setRemark(x.getRemark());
                list2.add(baseSqlconfig2);
            }
            message = dBServerServiceImpl.saveBaseSqlConfig(list2);
            if ("success".equals(message)) {
                redisCatchCensus.setExtAllSql(xString);
            }
            jsonResult.setMsg("添加成功");
            jsonResult.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setMsg("添加失败");
            jsonResult.setSuccess(false);
        }
        return jsonResult;
    }

    /**
     * 保存显示字段（暂时不用）
     *
     * @param queryFileds
     * @param request
     * @return
     */
    @RequestMapping(
            value = "/saveFiledConfig",
            method = RequestMethod.POST,
            consumes = "application/json")
    @ResponseBody
    public Object saveFiledConfig(@RequestBody QueryFiled[] queryFileds, HttpServletRequest request) {

        // String message = dBServerServiceImpl.saveFiledConfig(list);
        boolean cleanOldData = false;
        String message = "";
        for (QueryFiled queryField : queryFileds) {
            if (!cleanOldData) {
                cfgExtSqlService.deleteByServiceId(queryField.getServiceid());
                cleanOldData = true;
            }

            BaseSqlFieldType baseSqlFieldType = new BaseSqlFieldType();
            baseSqlFieldType.setGuid(UUID.randomUUID().toString());
            baseSqlFieldType.setFieldName(queryField.getParametercode());
            baseSqlFieldType.setServiceId(queryField.getServiceid());
            baseSqlFieldType.setFieldJavaType(queryField.getFieldJavaType());
            baseSqlFieldType.setCreateDate(new Date());
            baseSqlFieldType.setNote(queryField.getNote());
            int flag = cfgExtSqlService.insertBaseSqlFieldType(baseSqlFieldType);
            if (flag == 1) {
                message = "success";
            }
        }

        JsonResult jsonResult = new JsonResult();
        if ("success".equals(message)) {
            // 保存必填信息
            this.saveSQLQueryFiled(queryFileds);
            jsonResult.setMsg("保存成功");
            jsonResult.setSuccess(true);
        }

        return jsonResult;
    }


    void saveSQLQueryFiled(QueryFiled[] queryFileds) {
        List<BaseQueryfield> collect = Arrays.stream(queryFileds).map(item -> {
            BaseQueryfield baseQueryfield = new BaseQueryfield();
            baseQueryfield.setServiceid(item.getServiceid());
            baseQueryfield.setServicetype(4);
            baseQueryfield.setShowtype(0);
            baseQueryfield.setParametercode(item.getParametercode());
            baseQueryfield.setParametervalue(item.getParametervalue());
            baseQueryfield.setRequiredFlag(item.getRequiredFlag());
            return baseQueryfield;
        }).collect(Collectors.toList());
        // 批量保存
        baseQueryfieldService.saveQueryFiled(collect);
    }

    @RequestMapping(
            value = "/autoManageFieldType",
            method = RequestMethod.POST,
            consumes = "application/json")
    @ResponseBody
    public Object autoManageFieldType(@RequestBody QueryFiled[] queryFileds) {
        // here is parse sql , then get parameter , if don't existed parameter delete
        if (queryFileds == null)
            return null;

        String serviceId = queryFileds[0].getServiceid();
        CfgExtsql cfgExtsql = cfgExtSqlService.selectCfgSqlByPrimary(serviceId);
//        Map<String, String> realNeedParameterMap = XCommonUtils.extractPlaceHolderColumnObjectByParseSql(cfgExtsql.getDtSql());
        String sql = cfgExtsql.getDtSql();
        Map<String, String> hashMap = new HashMap<>();
        if (Objects.equals(cfgExtsql.getParamtype(), ParseSQLEnum.freemarker.getType())) {
            hashMap = XCommonUtils.extractPlaceHolderColumnObjectByParseSql(sql);
        } else {
            SqlData sqlData = ognlParseSQLStrategy.parseSQLGetField(sql, new HashMap<>());
            for (InputParam inputParam : sqlData.getParamList()) {
                hashMap.put(inputParam.getName(), inputParam.getJavaType());
            }
        }
        // delete all
        cfgExtSqlService.deleteByServiceId(serviceId);

        // find newest data ,and remove uesless
        String message = "";
        for (QueryFiled queryField : queryFileds) {
            if (!hashMap.containsKey(queryField.getParametercode()))
                continue;

            BaseSqlFieldType baseSqlFieldType = new BaseSqlFieldType();
            baseSqlFieldType.setGuid(UUID.randomUUID().toString());
            baseSqlFieldType.setFieldName(queryField.getParametercode());
            baseSqlFieldType.setServiceId(queryField.getServiceid());
            baseSqlFieldType.setFieldJavaType(StringUtils.isEmpty(queryField.getFieldJavaType()) ? hashMap.get(queryField.getParametercode()) : queryField.getFieldJavaType());
            baseSqlFieldType.setCreateDate(new Date());
            int flag = cfgExtSqlService.insertBaseSqlFieldType(baseSqlFieldType);
            if (flag == 1) {
                message = "success";
            }
        }

        JsonResult jsonResult = new JsonResult();
        if ("success".equals(message)) {

            jsonResult.setMsg("保存成功");
            jsonResult.setSuccess(true);
        }

        return jsonResult;
    }


    /**
     * 通过数据源标识获取表信息
     *
     * @param request
     * @return
     */
    @RequestMapping("/selectTableMap")
    @ResponseBody
    public Object selectTableMap(HttpServletRequest request) {
        String conn = null;
        Map<String, String> map = null;
        conn = request.getParameter("dbKey");
        map = dBServerServiceImpl.selectAllTableMap(conn);
        return map;
    }

    /**
     * 根据数据库的key值获取数据库的类型
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/selectDBType")
    @ResponseBody
    public boolean selectDBType(HttpServletRequest request) {
        boolean isSqlServer = false;
        String dbkey = request.getParameter("dbkey");
        String dbKeyType = dBServerServiceImpl.selectDbType(dbkey);
        if ("SQLSERVER".equals(dbKeyType)) {
            isSqlServer = true;
        }
        return isSqlServer;
    }

    //	PrjServiceExt getPrjServiceExt(String serviceCode);
    @RequestMapping(value = "/getServiceByCode")
    @ResponseBody
    public Object getPrjServiceExt(String serviceCode) {
        PrjServiceExt prjServiceExt = sysPrjServiceService.getPrjServiceExt(serviceCode);
        return prjServiceExt;
    }
}
